﻿using System;
using System.Web;
using System.IO;

namespace HttpUploader4.demoSql2005.db
{
	public partial class ajax_create_fid : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
        {
            string remoteHandle = Request.Params["callback"];
            string md5 = Request.Params["md5"];
            //string uid = Request.Form["uid"];
            string uid ="0";
            string systemId = Request.Params["SystemId"];
            string moduleId = Request.Params["ModuleId"];
            string belongId = Request.Params["BelongId"];
            string fileLength = Request.Params["fileLength"];
            string fileSize = Request.Params["fileSize"];
            HttpUploaderDB db = new HttpUploaderDB();

            bool hasReachFileLimit = db.HasReachFileLimit(systemId, moduleId, belongId, 1);
            if (hasReachFileLimit)
            {
                Response.Write(remoteHandle+"({\"error\":\"" + "此处您最多仅能上传" + 1 + "个文件"+"\"});");
                return;
            }

			//客户端使用的是encodeURIComponent编码，
            string pathLocal = HttpUtility.UrlDecode(Request.Params["pathLocal"]);//utf-8解码
			string json = "0";

			//参数为空
			if (md5 == null|| uid == null|| fileSize == null)
			{
                Response.Write(remoteHandle+"({\"error\":\"" + "参数不能为空" + "\"});");
				return;
			}

			if (md5.Length > 0&& uid.Length > 0&& fileSize.Length > 0)
			{
				xdb_files inf = new xdb_files();
				inf.FileNameLocal = Path.GetFileName(pathLocal);
				inf.FilePathLocal = pathLocal;
				//以MD5方式命名。
				inf.FileNameRemote = md5 + Path.GetExtension(pathLocal).ToLower();
				//以原始文件名称命名。
				//inf.FileNameRemote = inf.FileNameLocal;

				//数据库存在相同文件
				if ( db.GetFileInfByMd5(md5, ref inf))
				{
					inf.FileNameLocal = Path.GetFileName(pathLocal);
					inf.FilePathLocal = pathLocal;
                    inf.uid = int.Parse(uid);//将当前文件UID设置为当前用户UID
                    inf.SystemId =systemId;
                    inf.ModuleId =moduleId;
                    inf.BelongId =belongId;
					inf.IsDeleted = false;
					inf.fid = db.Add(ref inf);
				}//数据库不存在相同文件
				else
				{
					HttpUploaderCfg cfg = new HttpUploaderCfg();
					cfg.CreateUploadPath(systemId);

                    inf.uid = int.Parse(uid);//将当前文件UID设置为当前用户UID
                    inf.SystemId = systemId;
                    inf.ModuleId = moduleId;
                    inf.BelongId = belongId;
					inf.FileSize = fileSize;
					inf.FileMD5 = md5;
					inf.FileLength = Convert.ToInt32(fileLength);
					inf.FilePathRemote = Path.Combine(cfg.GetUploadPath(),inf.FileNameRemote);
					inf.FilePathRelative = Path.Combine(cfg.GetRelatPath(),inf.FileNameRemote);
					inf.fid = db.Add(ref inf);
				}
				json = inf.ToJson();
			}
            Response.Write(remoteHandle+"(" + json + ");");
		}
	}
}